package cn.itsource.basic.other.aop;

import cn.itsource.basic.other.annotation.Repeat;
import cn.itsource.basic.other.config.exception.BusinessException;
import cn.itsource.basic.util.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class RepeatAop {

    @Autowired
    private RedisService redisService;

    @Pointcut("@annotation(repeat)")
    public void cut(Repeat repeat){

    }

    @Before("cut(repeat)")
    public void repeat(Repeat repeat){
        //1.获取request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        //2.获取
        //3.拦截同一个ip一直获取验证码
        String ipPhoneStr = request.getRemoteAddr() + request.getRequestURI();

        String res = redisService.getKeyObjectValue(ipPhoneStr, String.class);
        if (res != null){
            throw new BusinessException("哥哥，你太快了");
        }
        //存ip到redis中,保持1分钟,1分钟内重复获取抛出上面的异常
        redisService.setStringKeyAndValue(ipPhoneStr,"123456",repeat.value());

    }

}
